import React, { useEffect, useState } from 'react'
import Web3 from 'web3'
export default function Home() {
    const [isPrint, setIsPrint] = useState(false)
    const [logArr, setLogArr] = useState(['日志初始化成功'])
    const [account, setAccount] = useState(null)
    const [chainId, setChainId] = useState(null)

    useEffect(() => {
        const openPrint = () => {
            if (typeof window.ethereum !== 'undefined') {
                // 添加各种监听事件
                console.log(typeof window.ethereum)
                window.ethereum.on('accountsChanged', (account) => {
                    setAccount(account[0])
                });

                window.ethereum.on('chainChanged', (chainId) => {
                    setChainId(parseInt(chainId, 16))
                });
            } else {
                alert('未安装matemask插件')
            }
        }

        const initInfo = async () => {
            const web3 = new Web3(Web3.givenProvider)
            const account = await web3.eth.getAccounts()
            const chainId = await web3.eth.getChainId()
            setAccount(account)
            setChainId(chainId)
            openPrint()
        }

        initInfo()
    }, [])

    useEffect(() => {
        console.log(account, chainId)
        if (!account || !chainId) return
        if (account === '') return setLogArr([...logArr, '连接断开'])
        setLogArr([...logArr, '连接状态切换成功，当前所在网络chainID：' + chainId + '，当前账户：' + account])
    }, [account, chainId])

    // 连接matemask
    const handelClickConnect = () => {
        window.ethereum.request({
            method: 'eth_requestAccounts'
        }).then((account) => {
            alert('已连接')
        }).catch((_err) => {
            console.log('你取消了连接')
        })
    }

    // 添加BOT到钱包用户资产
    const handelClickWatchAsset = () => {
        window.ethereum.request({
            method: 'wallet_watchAsset',
            params: {
                type: 'ERC20',
                options: {
                    address: '0xabf690e2ebc6690c4fdc303fc3ee0fbfeb1818ed',
                    symbol: 'BOT',
                    decimals: 18,
                    image: '',
                },
            },
        }).then((success) => {
            if (success) {
                console.log('FOO successfully added to wallet!')
            } else {
                throw new Error('Something went wrong.')
            }
        })
            .catch(console.error)
    }

    // 发起以太坊转账
    const handelClickSend = async () => {
        const fromAccount = window.ethereum.selectedAddress
        const web3 = new Web3(Web3.givenProvider)
        const gas = window.ethereum.getGasPrice
        const params = [{
            "from": fromAccount,
            "to": "0xb02B693f23AF560c2eaCC5543e08037323889902",     // 2.9541 ETH
            "gas": '0x76c0', // 30400
            "gasPrice": web3.utils.toHex(web3.utils.toWei('1000', 'Gwei')),
            "value": web3.utils.toHex(web3.utils.toWei('0.1', 'ether')),
            "data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
        }]

        window.ethereum.send({
            method: 'eth_sendTransaction',
            params: params,
            from: fromAccount, // Provide the user's account to use.
        }, (err, data) => {
            console.log(err)
            console.log(data)
        })
    }

    const handelClickisMateMask = () => {
        const isMetaMaskInstalled = () => {
            //Have to check the ethereum binding on the window object to see if it's installed
            const { ethereum } = window;
            return Boolean(ethereum && ethereum.isMetaMask);
        }

        if (isMetaMaskInstalled()) {
            alert('插件已安装')
        } else {
            alert('插件未安装')
        }
    }



    return (
        <div>
            <button onClick={handelClickisMateMask}>检测MateMask 插件安装</button>
            <span>  </span>
            <button onClick={handelClickConnect}>连接matemask</button>
            <span>  </span>
            <button onClick={handelClickWatchAsset}>添加BOT到钱包资产</button>
            <span>  </span>
            <button onClick={handelClickSend}>发起0.1 ETH 转账</button>
            <ul>
                <h3>连接日志：</h3>
                {logArr.map((item, index) => {
                    return <p key={index}>{index}. {item}</p>
                })}
            </ul>
        </div>
    )
}
